#include <iostream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "Log.hpp"
#include "Common.hpp"
#include "Protocol.hpp"

using namespace LogModule;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: " << argv[0] << " <server_ip> <server_port>" << std::endl;
        return 1;
    }
    std::string server_ip = argv[1];
    int server_port = ::atoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cout << "Error in creating socket" << std::endl;
        return 1;
    }
    struct sockaddr_in client_addr;
    memset(&client_addr, 0, sizeof(client_addr));
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(server_port);
    client_addr.sin_addr.s_addr = inet_addr(server_ip.c_str());

    int ret = ::connect(sockfd, CONV(&client_addr), sizeof(client_addr));
    if (ret < 0)
    {
        std::cout << "Error in connecting to server" << std::endl;
        return 1;
    }
    std::cout << "Connected to server" << std::endl;

    std::string message;
    while (true)
    {
        int x, y;
        char oper;
        std::cout << "x: ";
        std::cin >> x;
        std::cout << "y: ";
        std::cin >> y;
        std::cout << "operator (+,-,*,/,%): ";
        std::cin >> oper;
        // 序列化
        request req(x, y, oper);
        req.Serialization(message);

        Encode(message);

        // std::cout<<"message:  ";
        // std::getline(std::cin,message);

        int n = ::write(sockfd, message.c_str(), message.size());
        if (n > 0)
        {
            char buffer[1024];
            int m = ::read(sockfd, buffer, sizeof(buffer));
            if (m > 0)
            {
                buffer[m] = 0;
                std::string package = buffer;
                std::string content;
                Decode(package, &content);
                response resp;
                resp.deserialization(content);

                // 6. 得到结构化数据
                std::cout << resp.Result() << "[" << resp.Code() << "]" << std::endl;
            }
            else
                break;
        }
        else
            break;
    }
    close(sockfd);

    return 0;
}